<?php

namespace app\models;

use Yii;
use app\models\SamplePositionElse;

/**
 * This is the model class for table "sample_position".
 *
 * @property integer $pk_id
 * @property integer $pt_id
 * @property integer $from_id
 * @property string $xna_id
 * @property integer $xna_type
 * @property string $case
 * @property integer $case_a
 * @property integer $case_b
 * @property integer $xna_x
 * @property integer $xna_y
 * @property integer $xna_z
 * @property string $crt_name
 * @property string $crt_time
 * @property SamplePositionElse $else
 */
class SamplePosition extends \yii\db\ActiveRecord
{
    public $part;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sample_position';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pt_id', 'from_id', 'xna_id', 'xna_type', 'crt_name', 'crt_time'], 'required'],
            // [['pt_id', 'from_id', 'xna_type', 'case_a', 'case_b', 'xna_x', 'xna_y', 'xna_z'], 'integer'],
            [['pt_id', 'from_id', 'xna_type', 'xna_x', 'xna_y', 'xna_z'], 'integer'],
            [['case_a', 'case_b'], 'string', 'max' => 2],
            [['crt_time'], 'safe'],
            [['xna_id', 'case', 'crt_name'], 'string', 'max' => 20],
            [['xna_id'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'pk_id' => 'Pk ID',
            'pt_id' => 'Pt ID',
            'from_id' => 'From ID',
            'xna_id' => '编号',
            'xna_type' => '种类',
            'case' => '盒名',
            'case_a' => 'A',
            'case_b' => 'B',
            'xna_x' => 'X',
            'xna_y' => 'Y',
            'xna_z' => 'Z',
            'crt_name' => '修改人',
            'crt_time' => '修改时间',
        ];
    }

    public function getM() {
        return $this->hasOne(SamplePositionElse::className(), ['from_id' => 'xna_id']);
    }

    public static function checkEnough($type)
    {
        $origins = SamplePosition::find()->where(['pt_id' => Yii::$app->session->get('pt_id'), 'xna_type' => $type])->all();
        $origins_key = [];

        foreach ($origins as $origin) {
            $origins_key[] = $origin->xna_id."-M";
        }
        
        $type = ($type == 1) ? 'dna' : 'rna';
        $countM = SamplePositionElse::find()->where(['in', 'xna_id', $origins_key])->count();

        $session = Yii::$app->session->set('warn_'.$type, ($countM == count($origins) - 1) ? 1 : 0);
    }
}
